package vn.info.vietnaminfo;

import java.util.ArrayList;

import org.w3c.dom.Document;

import vn.info.vietnaminfo.direction.GMapV2Direction;
import vn.info.vietnaminfo.lazylist.ImageLoader;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.FragmentActivity;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class MapActivity extends FragmentActivity implements LocationListener,
OnMarkerClickListener, OnInfoWindowClickListener,LocationSource {

	GoogleMap mMap;
	private LatLng SHOP_LOCATION;
	private LatLng CURRENT_LOCATION;
	private Bundle extra;
	private String nameShop,des,address,groupName,owner,phone,imgSrc;
	private double lng,lat;
	private Marker markerSHOP_ON_MAP_END;
	private ImageView v;
	private GMapV2Direction md;
	private OnLocationChangedListener mListener;

	private View mWindow;
	class CustomInfoWindowAdapter implements InfoWindowAdapter {

		// These a both viewgroups containing an ImageView with id "badge" and two TextViews with id
		// "title" and "snippet".


		CustomInfoWindowAdapter() {
			mWindow = getLayoutInflater().inflate(R.layout.layout_custom_show_map, null);
		}

		@Override
		public View getInfoWindow(Marker marker) {
			render(marker, mWindow);
			return mWindow;
		}


		private void render(Marker marker, View view) {

			v = (ImageView) view.findViewById(R.id.badge);
			Log.v("aaa", "src = "+imgSrc);
			//imageLoader.DisplayImage(imgSrc,v);

			try
			{
				//				URL url = new URL(imgSrc);
				//				BitmapFactory.Options options = new BitmapFactory.Options();
				//				// will results in a much smaller image than the original
				//				options.inSampleSize=1; //try to decrease decoded image
				//				Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream(),null,options);
				//				v.setImageBitmap(bmp);
				//new syncTask().execute();

			}
			catch(Exception e)
			{
				e.printStackTrace();
			}

			String title = marker.getTitle();
			TextView titleUi = ((TextView) view.findViewById(R.id.title));
			if (title != null) {
				// Spannable string allows us to edit the formatting of the text.
				SpannableString titleText = new SpannableString(title);
				titleText.setSpan(new ForegroundColorSpan(Color.RED), 0, titleText.length(), 0);
				titleUi.setText(titleText);
			} else {
				titleUi.setText("");
			}

			String snippet = marker.getSnippet();
			TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
			if (snippet != null && snippet.length() > 12) {
				SpannableString snippetText = new SpannableString(snippet);
				snippetText.setSpan(new ForegroundColorSpan(Color.BLUE), 0, snippet.length(), 0);
				snippetUi.setText(snippetText);
			} else {
				snippetUi.setText("");
			}
		}

		@Override
		public View getInfoContents(Marker arg0) {
			// TODO Auto-generated method stub
			return null;
		}
	}

	private Context mContext;
	private ImageLoader imageLoader; 
	private LocationManager locationManager;
	private String provider;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_shop_direction);
		mContext = this;

		imageLoader = new ImageLoader(mContext);
		extra = getIntent().getExtras();

		nameShop = extra.getString("NAME");
		address = extra.getString("ADDRESS");
		des		= extra.getString("DESCRIPTION");
		groupName= extra.getString("GROUPNAME");
		owner = extra.getString("OWNER");
		phone = extra.getString("PHONE");
		imgSrc = extra.getString("IMGSRC");
		lat = extra.getDouble("LAT");
		lng = extra.getDouble("LONG");
		SHOP_LOCATION = new LatLng(lat, lng);

		md = new GMapV2Direction();

		// Getting Google Play availability status
		int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

		// Showing status
		if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

			int requestCode = 10;
			Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
			dialog.show();

		}else {	// Google Play Services are available	

			// Getting reference to the SupportMapFragment of activity_main.xml
			SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

			// Getting GoogleMap object from the fragment
			mMap = fm.getMap();

			//render se viet o day


			addMarkersToMap();

			mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());

			// Set listeners for marker events.  See the bottom of this class for their behavior.
			mMap.setOnMarkerClickListener(this);
			mMap.setOnInfoWindowClickListener(this);
			// Enabling MyLocation Layer of Google Map
			mMap.setMyLocationEnabled(true);		
			mMap.setLocationSource(this);


			// Getting LocationManager object from System Service LOCATION_SERVICE
			locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

			// Creating a criteria object to retrieve provider
			Criteria criteria = new Criteria();

			// Getting the name of the best provider
			provider = locationManager.getBestProvider(criteria, true);

			// Getting Current Location
			Location location = locationManager.getLastKnownLocation(provider);
			Log.v("hungcx", "lat lastknow = "+location.getLatitude());
			Log.v("hungcx", "long lastknow = "+location.getLongitude());
			
			if(location!=null){
				onLocationChanged(location);
			}

			locationManager.requestLocationUpdates(provider, 60000, 0, this);
			v = (ImageView) mWindow.findViewById(R.id.badge);
			imageLoader.DisplayImage(imgSrc,v);

		}

	}
	
	
	
	@Override
	public void onPause()
	{
		if(locationManager != null)
		{
			locationManager.removeUpdates(this);
		}

		super.onPause();
	}

	@Override
	public void onResume()
	{
		super.onResume();

		if(locationManager != null)
		{
			mMap.setMyLocationEnabled(true);
		}
	}
	

	private void addMarkersToMap() {
		// Uses a colored icon.

		// A few more markers for good measure.
		markerSHOP_ON_MAP_END = mMap.addMarker(new MarkerOptions()
		.position(SHOP_LOCATION)
		.title(nameShop)
		.snippet(address));

		int numMarkersInRainbow = 12;
        for (int i = 0; i < numMarkersInRainbow; i++) {
            mMap.addMarker(new MarkerOptions()
                    .position(new LatLng(
                            -30 + 10 * Math.sin(i * Math.PI / (numMarkersInRainbow - 1)),
                            135 - 10 * Math.cos(i * Math.PI / (numMarkersInRainbow - 1))))
                    .title("Marker " + i)
                    .icon(BitmapDescriptorFactory.defaultMarker(i * 360 / numMarkersInRainbow)));
        }
		// Creates a marker rainbow demonstrating how to create default marker icons of different
		// hues (colors).
	}


	@Override
	public void onLocationChanged(Location location) {

		 mListener.onLocationChanged( location );
		
		// Getting latitude of the current location
		double latitude = location.getLatitude();

		// Getting longitude of the current location
		double longitude = location.getLongitude();		

		// Creating a LatLng object for the current location
		CURRENT_LOCATION = new LatLng(latitude, longitude);
		Log.v("aa", "latLng = "+CURRENT_LOCATION);
		// Showing the current location in Google Map
		mMap.moveCamera(CameraUpdateFactory.newLatLng(CURRENT_LOCATION));

		// Zoom in the Google Map
		mMap.clear();
		//DrawDirection();

	}
	 	

	private void DrawDirection()
	{
		addMarkersToMap();
		mMap.animateCamera(CameraUpdateFactory.zoomTo(15));

		mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(CURRENT_LOCATION, 16));
		Log.v("aa", "CURRENT_LOCATION = "+CURRENT_LOCATION);
		Log.v("aa", "SHOP_LOCATION = "+SHOP_LOCATION);
		Document doc = md.getDocument(CURRENT_LOCATION, SHOP_LOCATION, GMapV2Direction.MODE_DRIVING);
		int duration = md.getDurationValue(doc);
		String distance = md.getDistanceText(doc);
		String start_address = md.getStartAddress(doc);
		String copy_right = md.getCopyRights(doc);

		ArrayList<LatLng> directionPoint = md.getDirection(doc);
		PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);

		for(int i = 0 ; i < directionPoint.size() ; i++) {			
			rectLine.add(directionPoint.get(i));
		}

		mMap.addPolyline(rectLine);
		// Setting latitude and longitude in the TextView tv_location
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub		
	}

	@Override
	public boolean onMarkerClick(final Marker marker) {
		// This causes the marker at Perth to bounce into position when it is clicked.
		//if (marker.equals(markerSHOP_ON_MAP_END)) 
		{

			Log.v("aa", "dasdsadsadas = "+CURRENT_LOCATION);
			final Handler handler = new Handler();
			final long start = SystemClock.uptimeMillis();
			Projection proj = mMap.getProjection();
			Point startPoint = proj.toScreenLocation(SHOP_LOCATION);
			startPoint.offset(0, -100);
			final LatLng startLatLng = proj.fromScreenLocation(startPoint);
			final long duration = 1500;

			final Interpolator interpolator = new BounceInterpolator();

			handler.post(new Runnable() {
				@Override
				public void run() {
					long elapsed = SystemClock.uptimeMillis() - start;
					float t = interpolator.getInterpolation((float) elapsed / duration);
					double lng = t * SHOP_LOCATION.longitude + (1 - t) * startLatLng.longitude;
					double lat = t * SHOP_LOCATION.latitude + (1 - t) * startLatLng.latitude;
					marker.setPosition(new LatLng(lat, lng));

					if (t < 1.0) {
						// Post again 16ms later.
						handler.postDelayed(this, 16);
					}
				}
			});
		}
		// We return false to indicate that we have not consumed the event and that we wish
		// for the default behavior to occur (which is for the camera to move such that the
		// marker is centered and for the marker's info window to open, if it has one).
		return false;
	}


	@Override
    public void activate(OnLocationChangedListener listener) 
    {
        mListener = listener;
    }
     
    @Override
    public void deactivate() 
    {
        mListener = null;
    }



	@Override
	public void onInfoWindowClick(Marker arg0) {
		// TODO Auto-generated method stub
		
	}


}